package com.klitors.creator;

import java.io.File;

import com.klitors.creator.utils.FileUtils;


/**
 * @author 66
 * @date 2016年10月17日
 */
public class CreateHandler implements FileFactory {
	Properties props;

	@Override
	public void createForSSH() {
		props.put("create_pattern", "ssh");
		mkdirs();
		createHbm();
		TextOut.file("Action.txt", props.path_action_java(), props);
		TextOut.file("struts.xml", props.path_struts_xml(), props);
	}

	public CreateHandler(Properties props) {
		this.props = props;
	}

	public void createForHibernate() {
		props.put("create_pattern", "hibernate");
		// 创建dao/servie文件夹及文件
		mkdirs();
		// 针对不同类型，生成特有的工具类
		createHibernateUtils();
		createHbm();
	}

	public void createForDbutils() {
		props.put("create_pattern", "dbutils");
		String jdbcutils = props.path_parent() + "/utils/JDBCUtils.java";
		TextOut.file("jdbcutils.txt", jdbcutils, props);
	}

	public void createForStruts() {
		props.put("create_pattern", "struts");
		TextOut.file("Action.txt", props.path_action_java(), props);
		TextOut.file("Action.xml", props.path_action_xml(), props);
		TextOut.file("struts.xml", props.path_struts_xml(), props);
	}

	private void createHbm() {
		File hbm = getFile(props.get("bean_path"), props.get("bean_name") + ".hbm.xml");
		TextOut.hbm(props, hbm);
	}

	private void createHibernateUtils() {
		String hibernateUtil = props.path_parent() + "/utils/HibernateUtil.java";
		TextOut.file("HibernateUtil.txt", hibernateUtil, props);
	}

	private void mkdirs() {
		String[] files = { "Dao.txt:/dao", "DaoImpl.txt:/dao/impl", "Service.txt:/service", "ServiceImpl.txt:/service/impl" };
		// 确定生成类型
		for (String str : files) {
			String[] split = str.split(":");
			String fileName = split[0];
			String filePath = split[1];
			String dao = FileUtils.mkPath(props.path_parent(), filePath, props.get("bean_name") + fileName.replace(".txt", "") + ".java");
			TextOut.file(fileName, dao, props);

		}
	}

	private File getFile(String dir, String fileName) {
		new File(dir).mkdirs();
		return new File(dir, fileName);
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}

}
